<template>
  <div>
    <Row>
      <Col>
        <Button
          type="primary"
          @click="handleAdd"
          v-hasC="{
            name: 'v1-clue-form-create',
            flag: 'v1/clue/form/create',
          }"
          >新增</Button
        >
      </Col>
    </Row>
    <Table
      :columns="columns"
      :data="data"
      :loading="loading"
      class="ivu-mt-16"
      :max-height="650"
    >
      <template slot="project_arr" slot-scope="{ row }">
        <Tag type="border" v-for="item in row.project_arr" :key="item">{{
          item
        }}</Tag>
      </template>
      <template slot="channel_arr" slot-scope="{ row }">
        <Tag type="border" v-for="item in row.channel_arr" :key="item">{{
          item
        }}</Tag>
      </template>
      <template slot="encrypt_str" slot-scope="{ row }">
        <Tooltip
          :content="
            `${baseUrl}/#/clueform/?formId=${encodeURIComponent(
              row.encrypt_str
            )}`
          "
          placement="top"
          max-width="200"
        >
          <a
            :href="`/#/clueform/?formId=${encodeURIComponent(row.encrypt_str)}`"
            v-if="row.template_name"
            target="_blank"
            ><Ellipsis
              :text="
                `${baseUrl}/#/clueform/?formId=${encodeURIComponent(
                  row.encrypt_str
                )}`
              "
              :length="30"
          /></a>
        </Tooltip>
      </template>
      <template slot="action" slot-scope="{ row }">
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-clue-form-update',
            flag: 'v1/clue/form/update',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-clue-form-update',
            flag: 'v1/clue/form/update',
          }"
        />
        <a
          @click="handleDel(row)"
          class="del"
          v-hasC="{
            name: 'v1-clue-form-delete',
            flag: 'v1/clue/form/delete',
          }"
          >删除</a
        >
      </template>
    </Table>

    <Page
      :total="total"
      class="ivu-mt-16"
      :modelValue="params.page"
      :page-size="params.pageSize"
      @on-change="changePage"
      show-total
      show-elevator
      show-sizer
      @on-page-size-change="changePageSize"
    />

    <Modal
      v-model="showForm"
      :title="isEdit ? '编辑' : '新增'"
      :draggable="true"
      :mask-closable="false"
      @on-cancel="handleCancel"
      footer-hide
    >
      <Form
        :model="formItem"
        :label-width="80"
        ref="formItem"
        :rules="createRules"
      >
        <FormItem label="名称" prop="name">
          <Input v-model="formItem.name" placeholder="请输入名称" />
        </FormItem>
        <FormItem label="部门" prop="department_id">
          <Select
            v-model="formItem.department_id"
            placeholder="请选择部门"
            @on-change="changeDept"
          >
            <Option
              :value="+item.value"
              v-for="item in departmentList"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="项目" prop="project_ids">
          <Select
            v-model="formItem.project_ids"
            multiple
            placeholder="请选择项目"
          >
            <Option
              :value="+item.value"
              v-for="item in projectList"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="渠道" prop="channel_ids">
          <Select
            multiple
            filterable
            v-model="formItem.channel_ids"
            placeholder="请选择渠道"
          >
            <OptionGroup
              v-for="item in channelList"
              :key="item.value"
              :label="item.label"
            >
              <Option
                :value="+el.value"
                v-for="el in item.children"
                :key="el.value"
                >{{ el.label }}</Option
              >
            </OptionGroup>
          </Select>
        </FormItem>

        <FormItem label="模板" prop="form_template_id">
          <Select v-model="formItem.form_template_id" placeholder="请选择模板">
            <Option
              :value="+item.value"
              v-for="item in templateList"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
      </Form>

      <div class="modalFoot">
        <Button @click="handleCancel()">取消</Button>
        <Button
          class="ivu-ml-16"
          :loading="btnLoading"
          type="primary"
          @click="handleSave()"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  formList,
  formCreate,
  formEditInfo,
  formUpdate,
  formDel,
  deptProjectCondition,
} from "@/api/clueform/index.js";
export default {
  name: "clueset",
  data() {
    return {
      loading: false,
      showForm: false,
      columns: [
        {
          title: "名称",
          key: "name",
          width: 120,
        },
        {
          title: "项目",
          slot: "project_arr",
          minWidth: 150,
        },
        {
          title: "渠道",
          slot: "channel_arr",
          minWidth: 160,
        },
        {
          title: "模板",
          key: "template_name",
          width: 140,
        },
        {
          title: "归属部门",
          key: "departement_name",
          width: 100,
        },
        {
          title: "表单网址",
          slot: "encrypt_str",
          minWidth: 120,
        },
        {
          title: "操作日期",
          key: "operate_time",
          width: 170,
        },
        {
          title: "操作人",
          key: "operate_name",
          width: 100,
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          width: 110,
        },
      ],
      data: [],
      total: 0,
      params: {
        page: 1,
        pageSize: 10,
      },
      isEdit: false,
      projectList: [],
      channelList: [],
      departmentList: [],
      templateList: [],
      btnLoading: false,
      formItem: {
        name: "",
        project_ids: [],
        channel_ids: [],
        department_id: "",
        form_template_id: "",
      },
      createRules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        project_ids: [
          {
            required: true,
            type: "array",
            message: "请选择项目",
            trigger: "change",
          },
        ],
        channel_ids: [
          {
            required: true,
            type: "array",
            message: "请选择渠道",
            trigger: "change",
          },
        ],
        department_id: [
          {
            required: true,
            type: "number",
            message: "请选择部门",
            trigger: "change",
          },
        ],
        form_template_id: [
          {
            required: true,
            type: "number",
            message: "请选择模板",
            trigger: "change",
          },
        ],
      },
      baseUrl: "",
    };
  },
  methods: {
    getData() {
      this.baseUrl = location.origin;
      this.loading = true;
      formList(this.params)
        .then((res) => {
          this.total = res.total;
          this.data = res.list;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getInfo(id) {
      formEditInfo({ id }).then((res) => {
        this.projectList = res.condition.project;
        this.channelList = res.condition.channel;
        this.departmentList = res.condition.department;
        this.templateList = res.condition.clue_template;
        if (id > 0) {
          this.formItem = {
            id: res.id,
            name: res.name,
            project_ids: res.project_ids,
            channel_ids: res.channel_ids,
            department_id: res.department_id,
            form_template_id: res.form_template_id,
          };
        }
      });
    },
    changePage(e) {
      this.params.page = e;
      this.getData();
    },
    changePageSize(e) {
      this.params.pageSize = e;
      this.getData();
    },
    initData() {
      this.formItem = {
        name: "",
        project_ids: [],
        channel_ids: [],
        department_id: "",
        form_template_id: "",
      };
      this.$refs.formItem.resetFields();
    },
    handleAdd() {
      this.initData();
      this.getInfo(0);
      this.isEdit = false;
      this.showForm = true;
    },
    handleDel(row) {
      this.$Modal.confirm({
        title: "删除确认",
        content: "删除后将不可恢复，是否确认删除",
        loading: true,
        onOk: () => {
          formDel({ id: row.id })
            .then(() => {
              this.$Message.success("删除成功！");
              this.getData();
              this.$Modal.remove();
            })
            .catch(() => {
              this.$Modal.remove();
            });
        },
      });
    },
    handleEdit(row) {
      this.initData();
      this.getInfo(row.id);
      this.isEdit = true;
      this.showForm = true;
    },
    handleCancel() {
      this.showForm = false;
    },
    changeDept(e) {
      this.formItem.project_ids = [];
      deptProjectCondition({ department_id: e }).then((res) => {
        this.projectList = res;
      });
    },
    handleSave() {
      this.$refs["formItem"].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          if (this.isEdit) {
            formUpdate(this.formItem)
              .then(() => {
                this.$Message.success("保存成功！");
                this.btnLoading = false;
                this.showForm = false;
                this.getData();
              })
              .catch(() => {
                this.btnLoading = false;
              });
          } else {
            formCreate(this.formItem)
              .then(() => {
                this.$Message.success("保存成功！");
                this.btnLoading = false;
                this.showForm = false;
                this.getData();
              })
              .catch(() => {
                this.btnLoading = false;
              });
          }
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.modalFoot {
  text-align: right;
  border-top: 1px solid #ddd;
  padding-top: 16px;
  margin-top: 24px;
}
.title {
  color: #999;
  margin-bottom: 15px;
}
</style>
